<?php
/**
 * Form Template for Booking View
 */
defined('_JEXEC') or die('Restricted access');

//add css and js
$document = & JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'components/com_roombooking/assets/css/datepicker/jquery.ui.all.css');

$document->addScript(JURI::base() . 'components/com_roombooking/assets/js/jquery/jquery-1.5.2.min.js');
$document->addScript(JURI::base() . 'components/com_roombooking/assets/js/datepicker/jquery.ui.core.js');
$document->addScript(JURI::base() . 'components/com_roombooking/assets/js/datepicker/jquery.ui.widget.js');
$document->addScript(JURI::base() . 'components/com_roombooking/assets/js/datepicker/jquery.ui.datepicker.js');
$document->addScript(JURI::base() . 'components/com_roombooking/assets/js/date.js');

JHTML::_('behavior.formvalidation');
$minTime = explode(':', $this->minTime);
$maxTime = explode(':', $this->maxTime);
$js = "
function disableRepeat(){
	var repeat_type = document.getElementById('repeat_type').value;
	if (repeat_type=='0'){
		document.getElementById('repeat_until').value='';
		document.getElementById('repeat_until').disabled=true;
	}
	else
		document.getElementById('repeat_until').disabled=false;
}

function clearRepeat(){
	if (document.getElementById('repeat_type').value=='0')
		document.getElementById('repeat_until').value='';
}


Window.onDomReady(function() {
       document.formvalidator.setHandler('date', function(value) {
     var start_date_arr = document.getElementById('start_date').value.split('-');
     var start_date = new Date(start_date_arr[0], start_date_arr[1]-1, start_date_arr[2], document.getElementById('start_hour').value, document.getElementById('start_minute').value );
     var end_date_arr = document.getElementById('end_date').value.split('-');
     var end_date = new Date(end_date_arr[0], end_date_arr[1]-1, end_date_arr[2], document.getElementById('end_hour').value, document.getElementById('end_minute').value );";

if (!$this->we_opening)
    $js.= " if (start_date.getDay()==0 || start_date.getDay()==6 || end_date.getDay()==0 || end_date.getDay()==6 ) 
     {
	window.alert('" . JText::_('NOBOOKINPAST') . "');
	return false;
     }";

$js.="if (end_date<=start_date){
		alert('" . JText::_('LATERENDDATE', true) . "');
		return false;
	}
	return true;
   }); 
   
   document.formvalidator.setHandler('start_date', function(value) {
	  var start_date_arr = document.getElementById('start_date').value.split('-');
	  var start_date = new Date(start_date_arr[0], start_date_arr[1]-1, start_date_arr[2], document.getElementById('start_hour').value, document.getElementById('start_minute').value );
	  var today=new Date ();
	  if (start_date< today){
		/*alert('" . JText::_('NOBOOKINPAST', true) . "');*/
		return false;
	 }";

if (!$this->we_opening)
    $js.=" if (start_date.getDay()==0 || start_date.getDay()==6 ) 
	{
		window.alert('" . JText::_('NOSUNSAT') . "');
		return false;
	}";

$js.="	return true;
      
	})
});

function check(value, control_minute){
	var where = (navigator.appName == 'Microsoft Internet Explorer') ? -1 : null;
	if(value==" . $maxTime[0] . "){
		control_minute.empty();
		for (var i = 0; i <= " . $maxTime[1] . "; i+=5) {
			newElem = document.createElement('option');
			if(i<10) {
				newElem.text = '0'+i;
				newElem.value = '0'+i;
			}
			else{
				newElem.text = i;
				newElem.value = i;
			}
			control_minute.add(newElem, where);
		}
	}
	else  if(value==" . $minTime[0] . "){
		control_minute.empty();
		for (var i = parseInt('" . $minTime[1] . "'); i <= 55; i+=5) {
			newElem = document.createElement('option');
			if(i<10) {
				newElem.text = '0'+i;
				newElem.value = '0'+i;
			}
			else{
				newElem.text = i;
				newElem.value = i;
			}
			control_minute.add(newElem, where);
		}
	}
	else if(control_minute.options.length!=13) {
		control_minute.empty();
		for (var i = 0; i <=55; i+=5) {
			newElem = document.createElement('option');
			if(i<10) {
				newElem.text = '0'+i;
				newElem.value = '0'+i;
			}
			else{
				newElem.text = i;
				newElem.value = i;
			}
			control_minute.add(newElem, where);
		}
	}
}
";
$document = & JFactory::getDocument();
$document->addScriptDeclaration($js);
?>
<div class="componentheading"><?php
if ($this->item->id != 0)
    echo JText::_('EDITBOOKING');
else
    echo JText::_('NEWBOOKING');
?>
</div>

<form action="#" method="post" name="adminForm" id="adminForm" class="form-validate"  enctype="multipart/form-data">
    <div class="col100">
        <p><?php echo JText::_('FIELDSREQUIRED'); ?></p>
        <table class="admintable">
            <tr>
                <td align="right" class="key">
                    <label for="short_description">
                        <?php echo JText::_('SHORTDESC'); ?>*:
                    </label>
                </td>
                <td>
                    <input class="required inputbox " type="text" name="short_description" id="short_description" style="width:300px" size="53" maxlength="250" value="<?php if (isset($this->item->short_description)) echo $this->item->short_description; ?>" />
                </td>
            </tr>
            <tr>
                <td align="right" class="key">
                    <label for="description">
                        <?php echo JText::_('DESC'); ?>:
                    </label>
                </td>
                <td>
                    <textarea  class="inputbox " name="description" id="description"  cols="50" rows="5" style="width:300px"><?php if (isset($this->item->description)) echo $this->item->description; ?></textarea>
                </td>
            </tr>
            <?php
            if ($this->item->id == 0) {
                echo '<tr>
			<td align="right" class="key">
				<label>
					' . JText::_('REPEAT') . ':
				</label for="repeat_type">
			</td>
			<td>
				<select name="repeat_type" id="repeat_type" onchange="javascript:disableRepeat();">
 					 <option   value="0"';
                if ($this->item->repeat_type == "0")
                    echo 'selected'; echo'>' . JText::_('NEVER') . '</option>
  				     <option value="day"';
                if ($this->item->repeat_type == "day")
                    echo 'selected'; echo'>' . JText::_('EVERYDAY') . '</option>
  				 	 <option  value="week"';
                if ($this->item->repeat_type == "week")
                    echo 'selected'; echo'>' . JText::_('EVERYWEEK') . '</option>
					<option value="2week"';
                if ($this->item->repeat_type == "2week")
                    echo 'selected'; echo'>' . JText::_('EVERY2WEEK') . '</option>					 
					<option value="month"';
                if ($this->item->repeat_type == "month")
                    echo 'selected'; echo'>' . JText::_('EVERYMONTH') . '</option>
					 <option value="year"';
                if ($this->item->repeat_type == "year")
                    echo 'selected'; echo'>' . JText::_('EVERYYEAR') . '</option>			</select>
			
				<label>' . JText::_('UNTIL') . ':
				</label for="repeat_until">
			
				
				' . /* JHTML::_('calendar', $this->item->repeat_until, 'repeat_until','repeat_until','%Y-%m-%d','class="inputbox validate-date" size="10" readonly="readonly" disabled="disabled" onchange="javascript:clearRepeat();"' ) */'<input type="text" onchange="javascript:clearRepeat();" disabled="" readonly="readonly" size="10" class="inputbox" value="" id="repeat_until" name="repeat_until">' . '
			</td>
<script>
if (document.getElementById("repeat_type").value=="0")
{
	document.getElementById("repeat_until").disabled=true;
	document.getElementById("repeat_until").value="";
}
else
{
	document.getElementById("repeat_until").disabled=false;
}
</script>
		</tr>';
            }
            ?>
            <tr>
                <td  align="right" class="key">
                    <label for="start_date">
                        <?php echo JText::_('STARTDATE'); ?>*:
                    </label>
                </td>
                <td>
                    <?php
                    $start_date = explode(' ', $this->item->start);
                    $start_date = $start_date[0];
                    //echo JHTML::_('calendar', $start_date,'start_date','start_date','%Y-%m-%d','class="required inputbox validate-start_date" size="10" readonly="readonly"'); 
                    ?>
                    <input type="text" readonly="readonly" size="10" class="required inputbox" value="<?php echo $start_date; ?>" id="from_date" name="start_date" />

                    <label for="start_hour">&nbsp;&nbsp;&nbsp;&nbsp;
                        <?php echo JText::_('HOUR'); ?>*:
                    </label>

                    <?php
                    $hours = array();
                    $hour = new stdClass();
//                    $hour->value = null;
//                    $hour->name = '--';
//                    array_push($hours, $hour);
                    for ($i = $minTime[0]; $i <= $maxTime[0]; $i++) {
                        $hour = new stdClass();
                        if (strlen($i) < 2)
                            $i = '0' . $i;
                        $hour->value = $i;
                        $hour->name = $i;
                        array_push($hours, $hour);
                    }
                    $minutes = array();
                    $minute = new stdClass();
//                    $minute->value = null;
//                    $minute->name = '--';
//                    array_push($minutes, $minute);
                    for ($i = 0; $i < 56; $i+=5) {
                        $minute = new stdClass();
                        if ($i < 10)
                            $i = '0' . $i;
                        $minute->value = $i;
                        $minute->name = $i;
                        array_push($minutes, $minute);
                    }
                    if (isset($this->item->start)) {
                        $selected_hour = explode(' ', $this->item->start);
                        $selected_hour = explode(':', $selected_hour[1]);
                        $selected_minutes = $selected_hour[1];
                        $selected_hour = $selected_hour[0];
                    } else {
                        $selected_hour = '--';
                        $selected_minutes = '--';
                    }
                    echo JHTML::_('select.genericlist', $hours, 'start_hour', 'class="required inputbox" onchange=check(this.value,document.getElementById(\'start_minute\'))', 'value', 'name', $selected_hour);
                    ?>
                    <label for="start_minute">
                        :
                    </label>
                    <?php echo JHTML::_('select.genericlist', $minutes, 'start_minute', 'class="required inputbox "', 'value', 'name', $selected_minutes); ?>
                </td>
            </tr>
            <tr>
                <td  align="right" class="key">
                    <label for="end_date">
                        <?php echo JText::_('ENDDATE'); ?>*:
                    </label>
                </td>
                <td>
                    <?php
                    $end_date = explode(' ', $this->item->end);
                    $end_date = $end_date[0];
                    if (isset($this->item->end)) {
                        $selected_hour = explode(' ', $this->item->end);
                        $selected_hour = explode(':', $selected_hour[1]);
                        $selected_minutes = $selected_hour[1];
                        $selected_hour = $selected_hour[0];
                    } else {
                        $selected_hour = '--';
                        $selected_minutes = '--';
                    }
                    //echo JHTML::_('calendar', $end_date,'end_date','end_date','%Y-%m-%d','class="required inputbox validate-date" size="10" readonly="readonly"' ); 
                    ?>
                    <input type="text" readonly="readonly" size="10" class="required inputbox" value="<?php echo $end_date; ?>" id="to_date" name="end_date">

                    <label for="end_hour">&nbsp;&nbsp;&nbsp;&nbsp;
                        <?php echo JText::_('HOUR'); ?>*:
                    </label>
                    <?php echo JHTML::_('select.genericlist', $hours, 'end_hour', 'class="required inputbox " onchange=check(this.value,document.getElementById(\'end_minute\'))', 'value', 'name', $selected_hour); ?>
                    <label for="end_minute">
                        :
                    </label>
                    <?php echo JHTML::_('select.genericlist', $minutes, 'end_minute', 'class="required inputbox"', 'value', 'name', $selected_minutes); ?>
                </td>
            </tr>
            <tr>
                <td align="right" class="key">
                    <label for="notes">
                        <?php echo JText::_('NOTES'); ?>:
                    </label>
                </td>
                <td>
                    <textarea  class="inputbox" name="notes" id="notes" cols="50" rows="5" style="width:300px"><?php if (isset($this->item->notes)) echo $this->item->notes; ?></textarea>
                </td>
            </tr>

            <tr>
                <td align="right" class="key">
                    <label>
                        <?php echo JText::_('ROOM'); ?>:
                    </label>
                </td>
                <td>
                    <?php if (isset($this->roomName)) echo $this->roomName . ' - ' . $this->getBuildOfRoom($this->item->id_room); ?>
                </td>
            </tr>
            <tr>
                <td align="right" class="key">
                    <label>
                        <?php echo "Total cost :"; ?>
                    </label>
                </td>
                <td>
                    <input id="total-cost" type="text" name="total" value="" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td align="right" class="key">
                    <input type="submit" class="button validate" value="<?php echo JText::_('BOOK'); ?> "/>
                </td>
            </tr>
        </table>
    </div>
    <div class="clr"></div>

    <input type="hidden" name="option" value="com_roombooking" />
    <input type="hidden" name="id" value="<?php echo $this->item->id; ?>" />
    <input type="hidden" name="id_room" value="<?php echo $this->item->id_room; ?>" />
    <input type="hidden" name="id_user" value="<?php if (isset($this->item->id_user)) echo $this->item->id_user; else echo JFactory::getUser()->id; ?>" />
    <input type="hidden" name="task" value="save" />
    <input type="hidden" name="controller" value="booking" />


</form>

<form action="#" method="post" id="back">
    <input type="hidden" name="option" value="com_roombooking" />
    <input type="hidden" name="task" value="cancel" />
    <input type="hidden" name="controller" value="booking" />
    <input type="hidden" name="id_room" value="<?php echo $this->item->id_room; ?>" />
    <input type="submit" class="button" value="<?php echo JText::_('CALENDAR'); ?>"/>
</form>

<!--minhbkpro-->
<script type="text/javascript">
    jQuery(function() {
        
        
//        var from_date = jQuery('#from_date');
//        var to_date = jQuery('#to_date');
//        var repeat_type = jQuery('#repeat_type');
//        var repeat_until = jQuery('#repeat_until');
        var all_date = jQuery( "#from_date,#to_date,#repeat_until" );
//        var from_date_val = jQuery('#from_date').val();
//        var to_date_val = jQuery('#to_date').val();
//        var repeat_until_val = jQuery('#repeat_until').val();
        var all = jQuery( "#from_date,#to_date,#repeat_until,#repeat_type" );
        
        all_date.datepicker();
        all_date.datepicker("option", "dateFormat", "yy-mm-dd");
        all_date.datepicker('option','minDate',0);
        
//        to_date.datepicker('option','minDate',from_date_val);
        var default_date = '<?php echo $start_date; ?>';
        if(default_date != ''){
            var arr = default_date.split('-');
            jQuery( "#from_date,#to_date" ).datepicker("setDate", new Date(arr[0],arr[1]-1,arr[2]) );
        }
        
        all.change(function(){
            check();
            countPrice();
        });
        check();
        checkHour();
        countPrice();
//        repeat_type.change(function(){
//            if(jQuery(this).val() == '0'){
////                from_date.datepicker('enable');
////                to_date.datepicker('enable');
//            }
//            else{
//                if(repeat_until.val() == ''){
////                    from_date.datepicker('disable');
////                    to_date.datepicker('disable');
//                }else{
////                    if(jQuery(this).val() == 'day')to_date.datepicker('disable');
////                    else to_date.datepicker('enable');
////                    from_date.datepicker('enable');
//                }
//            }
//            
//            //countPrice
//            countPrice();
//        });
//        from_date.datepicker('option', 'onSelect', function(date) {
//            from_date_val = date;
//            to_date.datepicker('option','minDate',date);
//            var date_arr = date.split('-');
//            var date_object = new Date();
//            date_object.setFullYear(date_arr[0],date_arr[1]-1,date_arr[2]);
//            var repeat_until_val = repeat_until.val();
//            var repeat_until_val_arr = repeat_until_val.split('-');
//            var repeat_until_object = new Date(repeat_until_val_arr[0],repeat_until_val_arr[1]-1,repeat_until_val_arr[2]);
//            var day_after = 0;
//            if(repeat_type.val() == 'day')to_date.datepicker("setDate", date_object );
//            else if(repeat_type.val() == 'week'){
//                day_after = 7 - date_object.getDay();
//                if(day_after == 7)day_after = 0;
//            }
//            else if(repeat_type.val() == '2week'){
//                day_after = 7 - date_object.getDay();
//                if(day_after == 7)day_after = 0;
//                day_after += 7*1;
//            }
//            else if(repeat_type.val() == 'month'){
//                var after = new Date(date_object.getFullYear(),date_object.getMonth()+1,0);
//                day_after = after.getDate() - date_object.getDate();
//                //                alert(day_after);
//            }
//            else if(repeat_type.val() == 'year'){
//                var after = new Date(date_object.getFullYear(),date_object.getMonth()+1,0);
//                day_after = after.getDate() - date_object.getDate();
//                for(var i = date_object.getMonth()+1;i <= 11;i++){
//                    after = new Date(date_object.getFullYear(),i,0);
//                    day_after += after.getDate()*1;
//                }
//            }
//            if(repeat_type.val() != 0){
//                date_object.setDate(date_object.getDate()*1+day_after*1);
//                var to_date_max_year = date_object.getFullYear();
//                var to_date_max_month = date_object.getMonth()+1;
//                var to_date_max_date = date_object.getDate();
//                var to_date_max_object = new Date(to_date_max_year,to_date_max_month-1,to_date_max_date);
//                if(to_date_max_object > repeat_until_object){
//                    var repeat_until_month = repeat_until_object.getMonth()*1+1*1;
//                    to_date.datepicker('option','maxDate',repeat_until_object.getFullYear()+'-'+repeat_until_month+'-'+repeat_until_object.getDate());
//                }
//                else{
//                    to_date.datepicker('option','maxDate',to_date_max_year+'-'+to_date_max_month+'-'+to_date_max_date);
//                }
//            }
//
//            //countPrice
//            countPrice();
//        });
//        repeat_until.datepicker('option', 'onSelect', function(date) {
//            repeat_until_val = date;
//            from_date.datepicker('option','maxDate',date);
//            to_date.datepicker('option','maxDate',date);
//            from_date.datepicker('enable');
//            if(repeat_type.val() != 'day')
//                to_date.datepicker('enable');
//            
//            //countPrice
//            countPrice();
//        });
//        
//        to_date.datepicker('option', 'onSelect', function(date) {
//            //countPrice
//            countPrice();
//        });
//        
        jQuery('#start_hour,#end_hour,#start_minute,#end_minute').change(function(){
            checkHour();
        });
    });
    function DateToObject(date){
        if(date){
            var arr = date.split('-');
            return new Date(arr[0],arr[1]-1,arr[2]);
        }else return null;
    }
    function ObjectToDate(object){
        if(object){
            var month = object.getMonth()*1+1*1;
            return object.getFullYear()+'-'+month+'-'+object.getDate();
        }else return '';
    }
    function check(){
        var repeat_type = jQuery('#repeat_type');
        var repeat_type_val = jQuery('#repeat_type').val();
        var repeat_until = jQuery('#repeat_until');
        var repeat_until_val = jQuery('#repeat_until').val();
        
        var from_date = jQuery('#from_date');
        var from_date_val = jQuery('#from_date').val();
        var to_date = jQuery('#to_date');
        var to_date_val = jQuery('#to_date').val();
        
        var all = jQuery( "#from_date,#to_date,#repeat_until,#repeat_type" );
        var all_date = jQuery( "#from_date,#to_date,#repeat_until" );
        
        var day_after = 0;
        var date_object = DateToObject(from_date_val);
        var repeat_until_object = DateToObject(repeat_until_val);
        
        //set to_date >= from_date
        to_date.datepicker('option','minDate',from_date_val);
        
        if(repeat_type_val != 0){
            switch(repeat_type_val){
                case 'day':
                    day_after = 0;
                    break;
                case 'week':
                    day_after = 7 - date_object.getDay();
                    if(day_after == 7)day_after = 0;
                    break;
                case '2week':
                    day_after = 7 - date_object.getDay();
                    if(day_after == 7)day_after = 0;
                    day_after += 7*1;
                    break;
                case 'month':
                    var after = new Date(date_object.getFullYear(),date_object.getMonth()+1,0);
                    day_after = after.getDate() - date_object.getDate();
                    break;
                case 'year':
                    var after = new Date(date_object.getFullYear(),date_object.getMonth()+1,0);
                    day_after = after.getDate() - date_object.getDate();
                    for(var i = date_object.getMonth()+1;i <= 11;i++){
                        after = new Date(date_object.getFullYear(),i,0);
                        day_after += after.getDate()*1;
                    }
                    break;
            }
            
            date_object.setDate(date_object.getDate()*1+day_after*1);
            var to_date_max_year = date_object.getFullYear();
            var to_date_max_month = date_object.getMonth()+1;
            var to_date_max_date = date_object.getDate();
            var to_date_max_object = new Date(to_date_max_year,to_date_max_month-1,to_date_max_date);
            
            if(repeat_until_object && to_date_max_object > repeat_until_object){
                var repeat_until_month = repeat_until_object.getMonth()*1+1*1;
                to_date.datepicker('option','maxDate',repeat_until_object.getFullYear()+'-'+repeat_until_month+'-'+repeat_until_object.getDate());
            }
            else{
                to_date.datepicker('option','maxDate',to_date_max_year+'-'+to_date_max_month+'-'+to_date_max_date);
            }
        }else to_date.datepicker('option','maxDate','');
        
    }
    function countPrice(){
        var repeat_type_val = jQuery('#repeat_type').val();
        var repeat_until_val = jQuery('#repeat_until').val();
        var from_date_val = jQuery('#from_date').val();
        var to_date_val = jQuery('#to_date').val();
        var start_hour = jQuery('#start_hour').val();
        var start_minute = jQuery('#start_minute').val();
        var end_hour = jQuery('#end_hour').val();
        var end_minute = jQuery('#end_minute').val();
        var oneLoop = 1;
        var cost = <?php echo $this->getCostOfRoom($this->item->id_room);?>
        
        if(from_date_val != ''&&to_date_val != ''&&start_hour != ''&&end_hour != ''&&((repeat_type_val == '0')||(repeat_type_val != '0'&&repeat_until_val != ''))){
//            alert('minhbkpro');
            var from_date = new Date(from_date_val.split('-')[0],from_date_val.split('-')[1]-1,from_date_val.split('-')[2]);
            var to_date = new Date(to_date_val.split('-')[0],to_date_val.split('-')[1]-1,to_date_val.split('-')[2]+1);
            var repeat_until = new Date(repeat_until_val.split('-')[0],repeat_until_val.split('-')[1]-1,repeat_until_val.split('-')[2]);
            from_date.setHours(start_hour);
            from_date.setMinutes(start_minute);
            to_date.setHours(end_hour);
            to_date.setMinutes(end_minute);
            var oneHour = 60*60*1000;	// hours*minutes*seconds*milliseconds
            var num_day = Math.round(Math.abs((from_date.getTime() - to_date.getTime())/(oneHour)));
//            alert(num_day);
            var loop = 1;
            if(repeat_type_val != 0){
                //loop
                if(repeat_type_val == 'day'){
                    oneLoop = 24*60*60*1000;
                }else if(repeat_type_val == 'week'){
                    oneLoop = 7*24*60*60*1000;
                }else if(repeat_type_val == '2week'){
                    oneLoop = 2*7*24*60*60*1000;
                }else if(repeat_type_val == 'month'){
                    oneLoop = 30*24*60*60*1000;
                }else if(repeat_type_val == 'year'){
                    oneLoop = 365*24*60*60*1000;
                }
                loop = Math.round(Math.abs((from_date.getTime() - repeat_until.getTime())/(oneLoop)));
            }
            jQuery('#total-cost').val(loop*cost*num_day);
//            alert(loop+'-'+cost+'-'+num_day);
        }
    }
    function checkHour(){
        var from_date_val = jQuery('#from_date').val();
        var to_date_val = jQuery('#to_date').val();
        if(from_date_val == to_date_val){
            var start_hour = jQuery('#start_hour').val();
            var end_hour = jQuery('#end_hour').val();
            if(start_hour > end_hour){
                jQuery('#end_hour option:contains('+start_hour+')').attr('selected','selected');
            }
            start_hour = jQuery('#start_hour').val();
            end_hour = jQuery('#end_hour').val();
            if(start_hour == end_hour){
                var start_minute = jQuery('#start_minute').val();
                var end_minute = jQuery('#end_minute').val();
                if(start_minute >= end_minute){
                    jQuery('#end_minute option:contains('+start_minute+')').next().attr('selected','selected');
                }
            }
        }
        
    }
</script>